<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Http\Requests\System\Config\StoreRequest;
use App\Http\Requests\System\Config\UpdateRequest;
use App\Http\Resources\System\Config\IndexResource;
use App\Models\System\Config;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Spatie\QueryBuilder\QueryBuilder;

class ConfigController extends Controller
{
    public function common(): JsonResponse
    {
        return $this->success(
            [
                'group' => Config::getDictGroup(),
            ]
        );
    }

    public function index(Request $request): JsonResponse
    {
        $list = QueryBuilder::for(Config::class, $request)
            ->allowedFilters(['id', 'group', 'title', 'name', 'value'])
            ->allowedSorts(['id', 'sort', 'created_at', 'updated_at'])
            ->paginate();

        return $this->success(IndexResource::collection($list));
    }

    public function store(StoreRequest $request): JsonResponse
    {
        $data = $request->validated();
        $row = new Config($data);
        $row->save();

        return $this->success([
            'id' => $row->id,
        ], 'store success');
    }

    public function update(UpdateRequest $request): JsonResponse
    {
        $data = $request->validated();
        $data = array_map(function ($value, $key) {
            return [
                'name' => $key,
                'value' => $value,
            ];
        }, array_values($data), array_keys($data));
        Config::upsert($data, ['name'], ['value']);

        return $this->success();
    }

    public function destroy(Config $config): JsonResponse
    {
        $config->delete();

        return $this->success([], 'delete success');
    }
}
